package ace.module.sms.core.impl.manager.supplier.impl;

import ace.cmp.i18n.api.MessageSourceAssertService;
import ace.module.sms.core.impl.dao.entity.SmsSupplier;
import ace.module.sms.core.impl.manager.supplier.SmsSupplierProviderMgr;
import ace.module.sms.supplier.api.SmsHandler;
import ace.module.sms.supplier.api.SmsHandlerFactory;
import ace.module.sms.supplier.api.dto.SupplierConfigDto;
import java.util.List;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/10/24 18:43
 */
@AllArgsConstructor
@Slf4j
@Component
public class SmsSupplierProviderMgrImpl implements SmsSupplierProviderMgr {
  private final MessageSourceAssertService assertService;
  private final List<SmsHandlerFactory> channelProviderFactories;

  @Override
  public SmsHandler getAndCheckProvider(SmsSupplier smsSupplier) {

    Optional<SmsHandlerFactory> smsChannelProviderOptional =
        this.channelProviderFactories.stream()
            .filter(smsChannelProvider -> smsChannelProvider.isSupport(smsSupplier.getType()))
            .findFirst();

    this.assertService.isTrue(
        smsChannelProviderOptional.isEmpty(),
        SmsSupplierProviderMgrImpl.class.getName()
            + ".error-supplier-provider-factory-cannot-be-null",
        "没有实现的短信提供者工厂");

    SupplierConfigDto configDto =
        SupplierConfigDto.builder()
            .id(smsSupplier.getId().toString())
            .config(smsSupplier.getConfig())
            .build();

    return smsChannelProviderOptional.get().getOrCreate(configDto);
  }
}
